package com.yc.cloud.socket.service.impl;

import cn.hutool.json.JSONUtil;
import com.yc.cloud.common.model.response.Outcome;
import com.yc.cloud.socket.service.SocketServer;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.websocket.Session;

/**
 * @author 杨智杰
 * @since 2021/9/24 14:02
 */
@Slf4j
@Service
public abstract class SocketServerImpl implements SocketServer {

    @Override
    public void onOpen(Session session) {
        log.info(session.getId() + "开启了链接!");
    }

    @Override
    public void onMessage(Session session, Object params) {
        log.info(session.getId() + "发送消息:" + params);
    }

    @Override
    public void onError(Session session, Throwable error) {
        log.error(error.getMessage(), error);
    }

    @Override
    public void onClose(Session session) {
        log.info(session.getId() + "关闭了链接!");
    }

    @Override
    @SneakyThrows
    public void sendMessage(Session session, Object data) {
        String jsonStr = JSONUtil.toJsonStr(Outcome.success().setData(data));
        session.getBasicRemote().sendText(jsonStr);
        log.info("向" + session.getId() + "发送消息:" + jsonStr);
    }
}
